package com.bh.ly.oa.uikit;

import java.io.IOException;
import java.util.Date;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * 
 * @author liangshun zhou
 * 
 */

public class UISwitch extends View {

	private Bitmap btn_on;
	private Bitmap btn_off;
	private Bitmap btn_slip;

	private Path path;// 裁减区域
	private boolean enabled = true; // 是否可用
	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	private boolean isOpen = false; // 是否打开
	
	private boolean isAnimation = false;
	
	private int dir;
	
	private static final int LEFT = 0;
	private static final int RIGHT = 1;

	/**
	 * 获得是否打开
	 * 
	 * @return
	 */
	public boolean isOpen() {
		return isOpen;
	}

	/**
	 * 设置是否打开
	 * 
	 * @param isOpen
	 */
	public void setOpen(boolean isOpen) {

		if (this.isOpen != isOpen) {
			this.isOpen = isOpen;
			if (isOpen) {
				startMoveToRight();
			} else {
				startMoveToLeft();
			}
		}

		
	}

	private boolean slip = false;
	private boolean danji = false;

	private boolean init = true;

	private float x;
	private float downX;
	private float moveX;
	private float offX; // 偏移量
	private float maxX;
	private float minX;

	private long downT;
	private long upT;
	private boolean outflag = false;

	private int x_on;
	private int x_off;
	private int x_slip;
	private int x_all;

	private OnSwitchChangedListener ChgLsn;// 设置监听

	public UISwitch(Context context) {
		super(context);
		try {
			init();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("UISwicth", e.getMessage());
		}
		// TODO Auto-generated constructor stub
	}

	public UISwitch(Context context, AttributeSet attrs) {
		super(context, attrs);
		try {
			init();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("UISwicth", e.getMessage());
		}
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		// TODO Auto-generated method stub
		if (isInEditMode())
			return;

		super.onLayout(changed, left, top, right, bottom);
	}

	@Override
	protected void onFinishInflate() {
		// TODO Auto-generated method stub

		if (isInEditMode())
			return;

		super.onFinishInflate();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View#onMeasure(int, int)
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		Log.e("UISwicth", "" + this.getWidth());
	}

	protected void onDraw(Canvas canvas) {
		// canvas.clipRect(new Rect(0, 0, getWidth(), getHeight()), new )

		// TODO Auto-generated method stub
		super.onDraw(canvas);
		x_all = this.getWidth();
		maxX = x_all - x_slip;
		minX = -1;
		/*
		 * Rect r=new Rect(0, 0, this.getWidth(), this.getHeight()); RectF
		 * rf=new RectF(r); Paint p1=new Paint(); p1.setColor(Color.WHITE);
		 * p1.setAntiAlias(true); canvas.drawRoundRect(rf, 8, 8, p1);
		 */

		if (init) // 初始化x坐标
		{
			// 初始化缩放
			int newWidth = this.getWidth();
			int newHeight = this.getHeight();
			float scaleWidth = ((float) newWidth) / btn_on.getWidth();
			float scaleHeight = ((float) newHeight) / btn_on.getHeight();
			Matrix matrix = new Matrix();
			matrix.postScale(scaleWidth, scaleHeight);
			btn_on = Bitmap.createBitmap(btn_on, 0, 0, btn_on.getWidth(),
					btn_on.getHeight(), matrix, true);
			btn_off = Bitmap.createBitmap(btn_off, 0, 0, btn_off.getWidth(),
					btn_off.getHeight(), matrix, true);
			// btn_slip = Bitmap.createBitmap(btn_slip, 0, 0,
			// btn_slip.getWidth(),
			// btn_slip.getHeight(), matrix, true);

			x_on = btn_on.getWidth();
			x_off = btn_off.getWidth();
			// x_slip = btn_slip.getWidth();
			x_slip = (int) (58 * scaleWidth);

			path.addRoundRect(new RectF(0, 0, newWidth, newHeight), x_slip / 2,
					x_slip, Path.Direction.CW);
			path.close();
			if (!isOpen)// 关闭
				x = minX;
			else
				x = maxX - x_slip;
		}

		canvas.save();
		canvas.clipPath(path);
		Paint p = new Paint();
		if (slip) {
			offX = moveX - downX;

			if (offX + x >= maxX) {

				canvas.drawBitmap(btn_off, maxX, 0, p);
				canvas.drawBitmap(btn_on, maxX - x_on + x_slip, 0, p);
				// canvas.drawBitmap(btn_slip, maxX, 0, p);
			} else if (offX + x <= minX) {
				canvas.drawBitmap(btn_off, minX, 0, p);
				canvas.drawBitmap(btn_on, minX - x_on + x_slip, 0, p);
				// canvas.drawBitmap(btn_slip, minX, 0, p);
			} else {
				canvas.drawBitmap(btn_off, x + offX, 0, p);
				canvas.drawBitmap(btn_on, x - x_on + x_slip + offX, 0, p);
				// canvas.drawBitmap(btn_slip, x + offX, 0, p);
			}
		} else {
			
			if (x >maxX)
			{
				x=maxX;
		
			}
				
			if (x < minX)
			{
				x=minX;

			}
			
			if(!enabled)
			{
				p.setAlpha(150);
			}
			canvas.drawBitmap(btn_off, x, 0, p);
			canvas.drawBitmap(btn_on, x - x_on + x_slip, 0, p);
		}

		if (ChgLsn != null && !init) {
			// 监听关闭打开
			if (x >= maxX) {
				if (!isOpen) {
					isOpen = true;
					ChgLsn.OnChanged(this, true);
				}

			}
			if (x <= minX) {
				if (isOpen) {
					isOpen = false;
					ChgLsn.OnChanged(this, false);
				}

			}
		}

		if (init)
			init = false;

		// p.setColor(Color.RED);
		// p.setStyle(Style.FILL);
		// canvas.drawPath(path, p);

		canvas.restore();

	}

	protected void init() throws IOException {

		btn_on = BitmapFactory.decodeStream(getContext().getAssets().open(
				"icon_on.png"));
		btn_off = BitmapFactory.decodeStream(getContext().getAssets().open(
				"icon_off.png"));
		// btn_slip = BitmapFactory.decodeStream(getContext().getAssets().open(
		// "white_btn.png"));

		path = new Path();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View#onTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean onTouchEvent(MotionEvent e) {
		// TODO Auto-generated method stub
		// return super.onTouchEvent(event);
		if (!enabled||isAnimation)
			return false;

		if (e.getX() < 0 || e.getX() > this.getWidth() || e.getY() < 0
				|| e.getY() > this.getHeight()) {
			touchCancel(e);

			return true;
		}

		switch (e.getAction())// 根据动作来执行代码
		{
		case MotionEvent.ACTION_MOVE:// 滑动
			// NowX = event.getX();
			slip = true;
			if(e.getX() - moveX>0)
				dir = RIGHT;
			else 
				dir = LEFT;
			moveX = e.getX();
			
			break;
		case MotionEvent.ACTION_DOWN:// 按下

			downX = e.getX(); // 按下的坐标
			moveX = downX;
			downT = new Date().getTime();
			break;
		case MotionEvent.ACTION_UP:// 松开
			touchUp(e);
			break;
		case MotionEvent.ACTION_CANCEL:// 取消
			touchCancel(e);
			break;
		default:
			break;

		}
		invalidate();// 重画控件
		return true;

	}

	public void touchUp(MotionEvent e) {

		slip = false;

		upT = new Date().getTime();
		Log.e("UISwicth", "" + (upT - downT));
		Log.e("UISwicth", "" + (e.getX() - downX));
		Log.e("UISwicth", "PointCount:" + e.getPointerCount());
		if (Math.abs(e.getX()-downX)<=10&&upT-downT<=100) // 单击事件
		{
//			setOpen(!isOpen);
			if(!isOpen)
			{
				startMoveToRight();
			}else
			{
				startMoveToLeft();
			}
		} else {
			x = x + offX; // x的新坐标
			if (x >= maxX)
				x = maxX;
			if (x <= minX)
				x = minX;
			startMove();
		}
	}

	private void touchCancel(MotionEvent e) {
		x = x + offX; // x的新坐标
		slip = false;
		upT = new Date().getTime();

		
		Log.e("UISwitch:", "downX:"+downX+" upX:"+e.getX());
		if(dir == RIGHT)
		{
//			x = maxX;
			startMoveToRight();
			Log.e("UISwitch:", "ToRight");
		}
		else if(dir==LEFT)
		{
//			x = minX;
			Log.e("UISwitch:", "ToLeft");
			startMoveToLeft();
		}
//		if (isOpen) {
//			
//		} else {
//			
//			if(e.getX()-downX>0)
//			{
//				x = maxX;
//				startMoveToRight();
//			}
//			else 
//			{
//				x = minX;
//				startMoveToLeft();
//			}
//		}
	}

	private void startMove() {
		new Thread() {

			public void run() {

				try {
					while (true) {
						// 向右移动
						if (x >= x_all / 2 - x_slip / 2) {
							x = x + 1;
							// 向左移动
						} else {
							x = x - 1;
						}

						if (x >= maxX)
						{
							x=maxX;
							break;
						}
							
						if (x <= minX)
						{
							x=minX;
							break;
						}
						postInvalidate();
						// invalidate();
						Thread.sleep(5);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();
	}

	private void startMoveToRight() {
		
		isAnimation = true;
		new Thread() {

			public void run() {

				try {
					while (true) {
						// 向右移动
						x = x + 1;
						postInvalidate();
						if (x >= maxX)
						{
							x = maxX;
							
							isAnimation = false;
							return;
						}
							
						Thread.sleep(5);
					}
					
					
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				

			}
		}.start();
	}

	private void startMoveToLeft() {
		
		isAnimation = true;
		new Thread() {

			public void run() {
				try {
					while (true) {
						x = x - 1;
						postInvalidate();
						if (x <= minX)
						{
							x=minX;
							isAnimation = false;
							return;
						}
							
						Thread.sleep(5);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
		}.start();
	}

	// 设置监听器
	public void SetOnChangedListener(OnSwitchChangedListener l) {
		ChgLsn = l;
	}

}
